package top.huxy.boot.config.argumentResolver;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import top.huxy.boot.config.Constant;
import top.huxy.boot.exception.RequestParamIllegalException;
import top.huxy.boot.model.dto.Pager;
import top.huxy.boot.util.StringUtils;

/**
 * @Classname PagerArgumentResolver
 * @Description PagerArgumentResolver
 * @Date 2021/8/30 20:43
 * @Created by huxy
 */
@Slf4j
public class PagerArgumentResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.getParameterType().isAssignableFrom(Pager.class);
    }

    @Override
    @SuppressWarnings("all")
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        String page = nativeWebRequest.getParameter(Constant.REQUEST_PAGE_NAME);
        String pageSize = nativeWebRequest.getParameter(Constant.REQUEST_PAGE_SIZE_NAME);

        int page0;

        int pageSize0;

        if (StringUtils.isEmpty(page)) {
            page0 = 1;
        } else {
            try {
                page0 = Integer.parseInt(page);
            } catch (NumberFormatException e) {
                throw new RequestParamIllegalException("page require a number,but it's '" + page + "'");
            }
        }
        if (StringUtils.isEmpty(pageSize)) {
            pageSize0 = 8;
        } else {
            try {
                pageSize0 = Integer.parseInt(pageSize);
            } catch (NumberFormatException e) {
                throw new RequestParamIllegalException("pageSize require a number,but it's '" + pageSize + "'");
            }
        }

        return new Pager(page0, pageSize0);
    }
}
